package com.example.movieratingbackend.service;


import com.example.movieratingbackend.model.Movie;
import com.example.movieratingbackend.repository.MovieRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Optional;

@Service
@Slf4j
public class MovieService {
    private final MovieRepository movieRepository;


    public MovieService(MovieRepository movieRepository) {
        this.movieRepository = movieRepository;
    }

    public Flux<Movie> getAllMovies() {
        return Flux.fromIterable(movieRepository.findAll());
    }

    public Mono<Movie> getMovieById(long id) {
        Optional<Movie> movieOptional = movieRepository.findById(id);

        return movieOptional.map(Mono::just).orElseGet(Mono::empty);

    }

    public Mono<Movie> submitRating(Long movieId, Integer rating) {
        Optional<Movie> movieOptional = movieRepository.findById(movieId);
        if (movieOptional.isEmpty()) {
            return Mono.empty();
        }
        return movieRepository.saveRating(movieId, rating);
    }


}